package leetcode.all;
import java.util.HashMap;

public class Solution560 {

    public static void main(String[] args) {
        int[] nums = new int[]{1};
        System.out.println(new leetcode.hot100.Solution560().subarraySum1(nums,0));
    }
    //前缀和
    public int subarraySum(int[] nums, int k) {
        int total = 0, sum = 0;
        int n = nums.length;
        HashMap<Integer,Integer> sumCount = new HashMap<>();
        sumCount.put(0,1);//啥也不选，和为0的子序列出现一次
        for(int i=0;i<n;i++){
            sum += nums[i];
            total += sumCount.getOrDefault(sum-k,0);
            sumCount.put(sum,sumCount.getOrDefault(sum,0)+1);
        }
        return total;
    }
    //
    public int subarraySum1(int[] nums, int k) {
        int count = 0, pre = 0;
        HashMap < Integer, Integer > mp = new HashMap < > ();
        mp.put(0, 1);
        for (int i = 0; i < nums.length; i++) {
            pre += nums[i];
            if (mp.containsKey(pre - k)) {
                count += mp.get(pre - k);
            }
            mp.put(pre, mp.getOrDefault(pre, 0) + 1);
        }
        return count;
    }
}
